// pages/loginIndex/loginIndex.js
var common_js = require("../../utils/common.js");
var url_js = require("../../utils/url.js");
var user_js = require("../../utils/user.js");
var const_js = require("../../utils/const.js");
var ubt_js = require("../../utils/ubt.js");
var name_js = require("../../utils/ubtButtonName.js");
var api = require("../../utils/apiRequest.js");
let notificationCenter = require('../../thridLib/WxNotificationCenter.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: null,
    loginBgUrl: url_js.imgUrl + "login_index_bg.png",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    //业务埋点
    ubt_js.myPageView(common_js.currentPageName(), options);
    //1.禁止转发
    wx.hideShareMenu();
    //2.初始化数据
    this.initData(options);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    // 业务埋点
    ubt_js.myPageViewOut(common_js.currentPageName());
  },

  //初始化数据
  initData: function(options) {
    let tempUserInfo = user_js.userInfo();
    this.setData({
      userInfo: tempUserInfo
    });
  },

  //一键登录
  onGetPhoneNumber: function(e) {
    var denied = e.detail.errMsg.indexOf("fail user deny") != -1;
    if (denied) return;
    //解析获取到的手机号码
    this.requestToDecryptMobile(e.detail);

    //埋点
    ubt_js.myClickButton(common_js.currentPageName(), name_js.loginIndexWx);
  },

  //解析手机号码
  requestToDecryptMobile: function(res) {
    let data = {
      code: this.data.userInfo.code,
      encryptedData: res.encryptedData,
      iv: res.iv
    }
    //chain request
    api.wxRequest(url_js.loginDecryptMobileUrl, data).then(res => {
      let loginData = {
        code: this.data.userInfo.code,
        loginType: 1,
        mobile: res.result,
        nickname: this.data.userInfo.wxUserInfo.nickName,
        openId: this.data.userInfo.openId,
        profilePhoto: this.data.userInfo.wxUserInfo.avatarUrl,
        sex: this.data.userInfo.wxUserInfo.gender,
        smsCode: "",
        unionId: ""
      }
      return api.wxRequest(url_js.loginLoginUrl, loginData);
    }).then(res => {
      this.handleLoginData(res);
    }).catch(err => {
      common_js.log(err);
    });
  },


  //处理获取手机验证码
  handleLoginData: function(res) {
    //1.保存当前用户信息
    var tempUserInfo = user_js.userInfo();
    tempUserInfo.userInfo = res.result;
    //保存用户信息
    user_js.saveUserInfo(tempUserInfo);
    //2. post notification
    notificationCenter.postNotificationName(const_js.loginSucessNoti);
    //3.继续购物
    wx.navigateBack({
      delta: 1
    });
  },

  //手机号验证码登录
  onLogin: function() {
    wx.navigateTo({
      url: '../login/login'
    });
  }
})